February 6, 2017

R can be rewardingly easy to use

R can be also a source of frustration

Let's do some simple calculations

options(digits=22)

1.1 - 0.2

Let's do some simple calculations

options(digits=22)

1.1 - 0.2
## [1] 0.9000000000000001332268

Let's do some simple calculations

Let's do some simple calculations

options(digits=22)

1.1 - 0.2
## [1] 0.9000000000000001332268

Reason: Machine representation of float (numbers with decimal points)

Usually differences are negligibly small

Let's talk about any() and all()

all(c())
any(c())

Let's talk about any() and all()

any(c())
## [1] FALSE

Let's talk about any() and all()

all(c())
## [1] TRUE

Let's talk about any() and all()

Solution in the help file:

Factors are super useful!

Working with factors in R

dat <- data.frame(measure = c('6','1', '1', '1', '2','10','4'))
as.numeric(dat$measure)
## [1] 5 1 1 1 3 2 4

Working with factors in R

str(dat$measure)
##  Factor w/ 5 levels "1","10","2","4",..: 5 1 1 1 3 2 4

R is full of (implicit) coercion

Implicit coercions is implicit!

dat$measure
## [1] 6  1  1  1  2  10 4 
## Levels: 1 10 2 4 6
c(dat$measure, c(22, 1))
## [1]  5  1  1  1  3  2  4 22  1

Working with factors in R

require('bananas') vs library('bananas')

require('bananas')
library('bananas')

require('bananas') vs library('bananas')

require('bananas')
## Loading required package: bananas
## Warning in library(package, lib.loc = lib.loc, character.only = TRUE,
## logical.return = TRUE, : there is no package called 'bananas'
library('banana')
## Error in library("banana"): there is no package called 'banana'

=> Use library in most cases

require('bananas') vs library('bananas')

x <- require('bananas')
x
## [1] FALSE
if(!x){
  install.packages('banana')
}

require('bananas') vs library('bananas')

<- vs =

x <- 1
x = 1

What's the difference?

<- vs =

In practice same functionality.

mean(new_var <- c(1,2))
## [1] 1.5
new_var
## [1] 1 2

What about <<- ?

var = 1
fun = function(x){var <<- x}
fun(2)
var
## [1] 2

Some advice

  • R help is helpful, use it!
  • Nice FAQ!

Meta facts about the talk:

Thanks!